package com.yihuier.yihuier.Util;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

public class ImageUtil {
    public static boolean changeImagesResolution(InputStream in , Path destRoute ,int width,int height,boolean proportion) throws IOException {
        if (Files.exists(destRoute)){
            return true;
        }

        Image img = ImageIO.read(in);
        // 判断图片格式是否正确
        if (img.getWidth(null) == -1) {
            return false;
        } else {
            int newWidth;
            int newHeight;
            // 判断是否是等比缩放
            if (proportion == true) {
                // 为等比缩放计算输出的图片宽度及高度
                double rate1 = ((double) img.getWidth(null))
                        / (double) width + 0.1;
                double rate2 = ((double) img.getHeight(null))
                        / (double) height + 0.1;
                // 根据缩放比率大的进行缩放控制
                double rate = rate1 > rate2 ? rate1 : rate2;
                newWidth = (int) (((double) img.getWidth(null)) / rate);
                newHeight = (int) (((double) img.getHeight(null)) / rate);
            } else {
                newWidth = width; // 输出的图片宽度
                newHeight = height; // 输出的图片高度
            }

            BufferedImage tag = new BufferedImage((int) newWidth,
                    (int) newHeight, BufferedImage.TYPE_INT_RGB);

            /*
             * Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的,优先级比速度高
            生成的图片质量比较好但速度慢
             */
            tag.getGraphics().drawImage(
                    img.getScaledInstance(newWidth, newHeight,
                            Image.SCALE_SMOOTH), 0, 0, null);
            Files.createFile(destRoute);
            // JPEGImageEncoder可适用于其他图片类型的转换
            return ImageIO.write(tag,"jpg",destRoute.toFile());
        }
    }
}
